#include <cstddef>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <vector>

#include "interpolate.h"
#include "quantize96.h"

using std::cout;
using std::endl;
using std::ifstream;
using std::ofstream;
using std::vector;

int main(int argc, char *argv[])
{
	if (argc<3) {
		cout << "Syntax: ac48to96 <inputfile> <outputfile>" << endl;
		cout << "inputfile  = 16bit 48kHz mono PCM file" << endl;
		cout << "outputfile =  8bit 96kHz mono raw PCM file" << endl;
		return EXIT_SUCCESS;
	}
	ifstream in (argv[1], std::ios::binary);
	if (!in) {
		cout << "error opening input file \"" << argv[1] << "\"" << endl;
		return EXIT_FAILURE;
	}
	in.seekg(44,std::ios::beg);
	ofstream out (argv[2], std::ios::binary);
	if (!out) {
		cout << "error opening output file \"" << argv[2] << "\"" << endl;
		return EXIT_FAILURE;
	}
	const int chunksize = 1024;
	vector<short> buff1 (chunksize);
	vector<short> buff2 (chunksize);
	char* const raw1 = reinterpret_cast<char*>(&buff1[0]);
	unsigned char* const raw1u = reinterpret_cast<unsigned char*>(&buff1[0]);
	twice_state ts = {{0}};
	quantize96_state qs;
	quantize96_init(&qs);
	cout << "processing ..." << endl;
	for (;;) {
		in.read(raw1,chunksize);
		if (in.eof()) break;
		twice_process(&ts,chunksize/2,&buff1[0],&buff2[0]);
		quantize96_process(&qs,1,8,chunksize,&buff2[0],&buff2[0]);
		for (int i=0; i<chunksize; ++i) {
			int s = buff2[i];
			if (s<-128) s=-128; else
			if (s> 127) s= 127;
			raw1u[i] = (128+s);
		}
		out.write(raw1,chunksize);
	}
	cout << "done." << endl;
}
